package com.coszero.utils.base

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import java.util.Arrays

/**
 * Desc： FragmentPagerAdapter的简单封装,
 * 可独立使用，也可以继承使用
 *
 *
 *
 * @author ： xmqian
 * Email:xmqian93@163.com
 * Date: 2019/7/11 10:29
 * @version 1
 */
class BaseTabViewPagerAdapter : FragmentPagerAdapter {
    private var mFragments: List<Fragment>?
    private var mTitles: MutableList<String>? = null

    /**
     * @param fm
     * @param fragments
     * @param titles 需要设置 TabLayout时传入的标题
     */
    constructor(fm: FragmentManager, fragments: List<Fragment>?, titles: Array<String?>) : this(
        fm,
        fragments!!, Arrays.asList<String>(*titles)
    )

    constructor(
        fm: FragmentManager,
        fragments: List<Fragment>,
        titles: MutableList<String>
    ) : super(fm) {
        mFragments = fragments
        mTitles = titles
    }

    /**
     * 不需要设置标题时使用
     *
     * @param fm
     * @param fragments
     */
    constructor(fm: FragmentManager, fragments: List<Fragment>) : super(fm) {
        mFragments = fragments
    }

    override fun getItem(position: Int): Fragment {
        return mFragments!![position]
    }

    override fun getCount(): Int {
        if (mFragments != null) {
            return mFragments!!.size
        }
        return 0
    }

    override fun getPageTitle(position: Int): CharSequence? {
        if (mTitles == null) return ""
        return mTitles!![position]
    }

    /**
     * 更新标题时使用，更新时标题数量必须大于界面数量
     *
     * @param position 更新的位置
     * @param title
     */
    fun setPageTitle(position: Int, title: String) {
        if (position >= 0 && position < mTitles!!.size) {
            mTitles!![position] = title
            notifyDataSetChanged()
        }
    }
}
